const jwt = require("jsonwebtoken")
const cookie_key = "token"
const secrect = "miyao_server" // 最好随机生成

/**
 * 颁发jwt
 */
module.exports.publish = function (res, info = {}, maxAge = 3600 * 24,) {
    const token = jwt.sign(info, secrect, {
        expiresIn: maxAge * 1000 // 过期时间
    })
    // 添加cookie
    // res.cookie(cookie_key, token, { maxAge, path: "/" })
    // 添加其他传输
    res.header("authorization", token)
}

/**
 * 认证jwt
 */
module.exports.verify = function (req) {
    // 尝试到cookie获取
    let token = req.cookies.token || req.headers.authorization
    if (!token) {
        return null // 没有token
    }
    // authorization: bearer token
    token = token.split(" ")
    token = token.length == 1 ? token[0] : token[1]

    // 验证是否有效
    try {
        return jwt.verify(token, secrect)
    } catch (e) {
        // 验证失败
        return null
    }
}